package com.qfedu.dao.impl;


import com.qfedu.dao.CartItemDao;
import com.qfedu.model.CartItem;
import com.qfedu.model.User;
import com.qfedu.utils.DruidUtil;
import jdk.nashorn.internal.scripts.JD;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

/**
 * @author 王海龙
 * @date 2023-04-18
 */
public class CartItemDaoImpl implements CartItemDao {
    private JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidUtil.getDataSource());
    //添加商品
    @Override
    public int addCartItme(CartItem cartItem) {
            String sql = "insert into cartItem values(null,?,?,?,?,?,?)";
            int row = jdbcTemplate.update(sql, cartItem.getCid(), cartItem.getId(), cartItem.getName(), cartItem.getPrice(),
                    cartItem.getCount(), cartItem.getTotalPrice());
            return row;
    }
    //合并
    @Override
    public int updateCartItem(CartItem cartItem) {
            String sql = "update cartItem set name=?,price=?,count=?,totalPrice=? where id=?";
            int update = jdbcTemplate.update(sql,cartItem.getName(),cartItem.getPrice(),cartItem.getCount(), cartItem.getTotalPrice(),cartItem.getId());
            return update;
    }
    //查询所有商品
    @Override
    public List<CartItem> findAll(User user) {
            String sql ="SELECT ci.* FROM  cartItem AS ci WHERE ci.cid=(SELECT c.cid  FROM t_user AS u ,cart AS c  WHERE u.id=c.id AND u.id=?)";
            List<CartItem> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(CartItem.class),user.getId());
            return list;

    }
    //删除制定商品
    @Override
    public int deleteItem(int i) {

            String sql = "delete from cartItem where id=?";
            int update = jdbcTemplate.update(sql, i);
            return update;
    }
    //清空购物车
    @Override
    public int truncate(int cid) {

            String sql = "delete from cartItem where cid=?";
            int row = jdbcTemplate.update(sql,cid);
            return row;
    }


    @Override
    public CartItem findCartItme(int cid) {
        String sql = "SELECT * FROM cartItem WHERE cid=?";
        List<CartItem> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(CartItem.class), cid);
        return query.get(0);

    }

}
